<template>
  <div class="chart-box">
    <el-row v-loading="chartLoading" class="funnel-row">
      <chart
        :option="chartData"
        ref="funnelChart"
        auto-resize
        style="width: 100%; height: 100%"
      ></chart>
    </el-row>
  </div>
</template>

<script>
import nt from '../../../../../network'
 import _ from 'lodash'
import mixinOption from '../../../../utils/mixinOption'
import parseApi from '../../../../utils/parseApi'

export default {
  // 单漏斗组件图
  name: 'custom-report-component-chart-funnel',
  props: {
    api: {},
    method: {
      type: String,
      default: 'get',
    },
    dataKey: {},
    mainTitle: {},
    time: {},
    componentData: {},
    changeSize: {},
    interval: {},
    mixinParam: {
      type: Object,
      default() {
        return {}
      },
    },
  },
  computed: {
    chartData() {
      switch (this.dataKey) {
        case 'common':
          return this.commonFunnelOption
          break
      }
    },
  },
  data() {
    return {
      comInterval: 0,
      chartLoading: false,
      isDataReady: false,
      commonfunnelData: {
        tooltip: {
          trigger: 'item',
          formatter: function (params) {
            var names = params.name.split(',')
            return names[0] + '<br />' + names[1]
          },
        },
        legend: {
          show: true,
          left: 'right',
          top: 'top',
          width: '40%',
          orient: 'horizontal',
          itemWidth: 9,
          itemHeight: 9,
          tooltip: {
            show: true,
            formatter: function (params) {
              var names = params.name.split(',')
              return names[0] + '<br />' + names[1]
            },
          },
          textStyle: {
            fontFamily: 'PingFangSC-Regular',
            fontSize: '14',
            fontWeight: '400',
            color: '#6D7C8B',
            rich: {
              name: {
                fontFamily: 'PingFangSC-Regular',
                fontSize: '13',
                fontWeight: '400',
                color: '#6D7C8B',
                width: 40,
                padding: [0, 0, 0, 10],
              },
              num: {
                fontFamily: 'PingFangSC-Regular',
                fontSize: '13',
                fontWeight: '400',
                color: '#6D7C8B',
                width: 40,
                align: 'right',
                padding: [0, 0, 0, 20],
              },
              per: {
                fontFamily: 'PingFangSC-Regular',
                fontSize: '13',
                fontWeight: '400',
                color: '#6D7C8B',
                width: 80,
                textStyle: { normal: { align: 'left' } },
                padding: [0, 0, 0, -5],
              },
            },
          },
          formatter: function (params) {
            let names = params.split(',')
            return (
              '{name|' +
              names[0] +
              '}{num|' +
              names[1] +
              '}{per|' +
              names[2] +
              '}'
            )
          },
          data: [],
        },
        series: [
          {
            type: 'funnel',
            label: {
              normal: {
                show: false,
              },
            },
            data: [],
          },
        ],
      },
      commonFunnelOption: {},
    }
  },
  watch: {
    componentData() {
      this.changeStyle()
    },
    changeSize() {
      this.$refs.funnelChart.resize()
    },
    'api.dsName': function () {
      this.getCommonfunnelData(this.changeStyle, true)
    },
    time() {
      this.changeParam()
    },
    mixinParam: {
      handler: function (val, oldVal) {
        let int = 0
        int = setInterval(() => {
          if (!this.chartLoading) {
            clearInterval(int)
            this.changeParam()
          }
        }, 50)
      },
      deep: true,
    },
  },
  methods: {
    changeParam() {
      if (this.api) {
        this.getCommonfunnelData(this.changeStyle)
        clearInterval(this.comInterval)
        if (this.interval) {
          this.comInterval = setInterval(() => {
            this.getCommonfunnelData(this.changeStyle)
          }, this.interval * 1000)
        }
      }
    },
    getCommonfunnelData(callback, newApi) {
      this.chartLoading = true
      let parsefunnelData = (data) => {
        if (
          !data ||
          JSON.stringify(data) === '{}' ||
          !data.valueList ||
          !data.valueList.length
        ) {
          data = {
            valueList: [
              //漏斗图的数值，
              {
                unit: '', //数据单位
                data: 0, //区域比例
                name: '', //图例和鼠标悬浮显示字
              },
            ],
          }
        }
        let yData = data.valueList
        let commonfunnelData = this.commonfunnelData

        let sum = 0
        yData.forEach((item) => {
          sum += item.data * 1
        })
        commonfunnelData.series[0].data = yData.map((item) => ({
          name:
            item.name +
            ',' +
            item.data +
            (item.unit || '') +
            ',' +
            (parseFloat(((item.data * 1) / sum) * 100) || 0).toFixed(2) +
            '%',
          value: item.data,
        }))
        commonfunnelData.legend.data = commonfunnelData.series[0].data
        this.chartLoading = false
        if (!this.isDataReady) {
          this.isDataReady = true
          this.$emit( 'dataReady')
        }
      }
      if (!this.api || !this.api.reqUrl) {
        let data = {
          valueList: [
            //漏斗图的数值，
            {
              unit: '个', //数据单位
              data: 60, //区域比例
              name: '标题一', //图例和鼠标悬浮显示字
            },
            {
              unit: '个',
              data: 40,
              name: '标题二',
            },
            {
              unit: '个',
              data: 10,
              name: '标题三',
            },
            {
              unit: '个',
              data: 80,
              name: '标题四',
            },
            {
              unit: '个',
              data: 100,
              name: '标题五',
            },
          ],
        }
        parsefunnelData(data)
        if (callback) {
          callback()
        }
      } else {
        nt.doRequest({
          method: 'post',
          uri: '/paas/chart-layout/v1/compdsconfig/testCompDSConfig',
          data: parseApi({
            api: this.api,
            time: this.time,
            mixinParam: this.mixinParam,
          }),
          onSuccess: (resp) => {
            let data = resp.data.content.content

            parsefunnelData(data)
            if (callback) {
              callback()
            }
          },
          onError: () => {
            parsefunnelData({})
            if (callback) {
              callback()
            }
          },
        })
      }
    },
    changeStyle() {
      let commonfunnelData = this.commonfunnelData
      let componentData = this.componentData
      commonfunnelData.grid = componentData.grid
      commonfunnelData.color = componentData.color
      for (let key in componentData.legend) {
        commonfunnelData.legend[key] = componentData.legend[key]
      }
      if (componentData.showPer) {
        // 展示百分比
        commonfunnelData.legend.formatter = function (params) {
          let names = params.split(',')
          return (
            '{name|' +
            names[0] +
            '}{num|' +
            names[1] +
            '}{per|' +
            names[2] +
            '}'
          )
        }
      } else {
        commonfunnelData.legend.formatter = function (params) {
          let names = params.split(',')
          return '{name|' + names[0] + '}{num|' + names[1] + '}'
        }
      }

      // 更新图表样式
      for (let key in componentData.series[0]) {
        if (
          [
            'funnelAlign',
            'sort',
            'left',
            'top',
            'width',
            'height',
            'label',
          ].indexOf(key) > -1
        ) {
          commonfunnelData.series[0][key] = componentData.series[0][key]
        }
      }

      commonfunnelData.series[0].label.emphasis = {
        show: !!componentData.series[0].label.normal.show,
      }
      this.commonFunnelOption = _.cloneDeep(commonfunnelData)
      if (componentData.code) {
        //给开发人员测试的，怕忘记删，生产环境就不打印了
        process.env.NODE_ENV === 'development' &&
          console.log(this.mainTitle + ' 混入前option', commonfunnelData)
        this.commonFunnelOption = mixinOption(
          this.commonFunnelOption,
          componentData.code
        )
        process.env.NODE_ENV === 'development' &&
          console.log(this.mainTitle + ' 混入后option', this.commonFunnelOption)
      }
      this.$refs.funnelChart.resize()
    },
  },
  mounted() {
    switch (this.dataKey) {
      case 'common':
        this.getCommonfunnelData(this.changeStyle)
        if (this.interval) {
          this.comInterval = setInterval(() => {
            this.getCommonfunnelData(this.changeStyle)
          }, this.interval * 1000)
        }
        break
    }
  },
  beforeDestroy() {
    clearInterval(this.comInterval)
  },
  emits: ['dataReady'],
}
</script>

<style scoped>
.chart-box {
  width: 100%;
  height: 100%;
  position: relative;
}
.funnel-row {
  width: 100%;
  height: 100%;
}
</style>
